#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "cast.h"
#include "client_list.h"




t_client find_client(client_list list, int socket){
	client_list tmp=list;

	if (tmp != NULL){
		t_client client = client_from_head_list(tmp);

		while( client != NULL)
		{
			if(get_number_socket(client) == socket)
			{
				return client;
			}
			client=client->next;
		}
	}
	return NULL;
}

void list_display(client_list list,int fd){

	client_list tmp = list;
	t_client client =client_from_head_list(tmp);

	while(client != NULL){

		int num_socket=get_number_socket(client);
		char* name=get_name(client);
		fprintf(stdout," name clicent ligne 42 %s\n",name);

		/*display*/

		char temp[50];
		sprintf(temp,"\nFrom list -> %s num_socket: %d\n",name,num_socket);
		sendline(fd,temp,strlen(temp));
		fprintf(stdout,"From list -> %s\n num_socket: %d\n",name,num_socket);

		client=client->next;
	}



}


void set_socket(int socket, t_client client ){
	client->num_socket=socket;
}

int get_number_socket(t_client client){
	if(client != NULL)
		return client->num_socket;
	return 0;
}
void set_name(char * name, t_client client){
	client->nameclient=name;
}

char* get_name(t_client client){

		return client->nameclient;
}

t_client client_from_end_list(client_list list){
	return list->end_list;
}
t_client client_from_head_list(client_list list){
	return list->head_list;
}

void search_delete(char *chaine) // Function to delete \n when typing
{
	char *p = strchr(chaine, '\n');

	if (p)
	{
		*p = 0;
	}
}

// Function to send to someone
void unicast(int fd, char *buffer, client_list list){
	sendline(fd,"Who do you want to send a message ?\n",strlen("Who do you want to send a message ?\n"));
	readline(fd,buffer,sizeof(buffer));
	search_delete(buffer);

	t_client client = client_from_head_list(list);

	while (client != NULL){
		sendline(fd,"Looking for client...\n",strlen("Looking for client...\n"));
		if (strcmp(buffer,get_name(client))==0){
			char* name= get_name(client);
			sendline(fd,"\nSend a message to ",strlen("\nSend a message to "));
			sendline(fd,name,strlen(name));
			sendline(fd,"\n",strlen("\n"));

			sendline(fd,"Type your message :\n",strlen("Type your message :\n"));
			readline(fd,buffer,sizeof(buffer));

			sendline(get_number_socket(client),buffer,strlen(buffer));

		}

			client=client->next;
	}




}
